﻿using Newtonsoft.Json.Linq;
//using Qiniu.Storage;
using Qiniu.IO;
using Qiniu.RS;
using Qiniu.RS.Model;
using Swirebev.PhotoDownload.Common;
using Swirebev.PhotoDownload.DAL;
using Swirebev.PhotoDownload.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using System.Reflection;
using System.Threading;
using Swirebev.PhotoDownload.Cloud;
using Swirebev.PhotoDownload.Common;
using Swirebev.PhotoDownload.DAL;
using Swirebev.PhotoDownload.Model;


namespace Swirebev.PhotoDownload.Cloud
{
    public class QiniuCloudHelper
    {
        private const string CloudTableName_File = "_File";

        private static QiniuCloudHelper _instance;
        public static QiniuCloudHelper Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new QiniuCloudHelper();
                }
                return _instance;
            }
        }

        public List<PhotoData> DownloadPhotos()
        {
            string keyFile = null;
            try
            {
                QiniuHelper qiniuHelp = new QiniuHelper(Settings.Instance.QiniuAccessKey, Settings.Instance.QiniuSecretKey, "");
                qiniuHelp.IsProxy = false;

                string qiniuBuckets = Settings.Instance.QiniuBuckets;
                string[] arrBuckets = qiniuBuckets.Split(',');

                BucketManager bm = qiniuHelp.BucketManager;
                int limit = Settings.Instance.DownloadPhotoQuantityOnce;   
                List<PhotoData> photoList = new List<PhotoData>();
               PhotoData photoData = null;
                

                      
                string businessTypeCd = null;           //业务类型代码
              
                
                string exName = null;
                string fullName = null;
                string strUrl = null;
                string accUrl = null;
                string saveUrl = null;
              // string time = null;
                string photoTime1 = null;
                // get value from configuration
                long putTime = Settings.Instance.putTime;
                long maxPutTime = Settings.Instance.putTime;


                

               // PhotoDownload.DAL.photoTime.GetPhotoInfo();   //从数据库获取照片信息

                List<PhotoMsessage> PhotoMsessageTask = photoTime.GetPhotoInfo();




                string photoEndDate = PhotoMsessageTask[0].PhotoDate;
                

                int status = 1;
               
              
                try
                {


                   
                foreach (PhotoMsessage photolist in PhotoMsessageTask)
                {

                    string shortName = photolist.PhotoName;
                    string photoUrl = photolist.PhotoUrl;
                   // string photoDate = photolist.PhotoDate;

                   

                    string[] strs = { "SEP" };
                           
                            string[] shortLength = shortName.Split(strs, StringSplitOptions.None);

                            if (shortLength.Length == 5)
                            {

                                             
                                photoData = new Model.PhotoData();

                                photoData.ObjectId = System.Guid.NewGuid().ToString("N");  //uuid
                                photoData.BusinessId = shortName.Split(strs, StringSplitOptions.None)[1];//业务编号
                                businessTypeCd = (shortName.Split(strs, StringSplitOptions.None))[3];//业务类型代码 420003:客户门招图片；420001:活动检查图片
                                photoData.BusinessTypeCd = businessTypeCd;
                                if (businessTypeCd == "420021")
                                    photoData.BusinessTypeCd = "420001";
                                else if (businessTypeCd == "420020")
                                    photoData.BusinessTypeCd = "420003";
                               

                                photoData.StoreId = (shortName.Split(strs, StringSplitOptions.None))[0];//客户编号
                                photoData.RouteId = (shortName.Split(strs, StringSplitOptions.None))[2];//线路编号
                               photoTime1 = (shortName.Split(strs, StringSplitOptions.None)[4]);//拍照时间
                               long photoTime2 =long.Parse(photoTime1.Substring(0, 10));

                              string   yuing= (photoUrl.Split('/'))[2];

                         

                               //照片上传时间的时间戳转换

                               System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                               dtDateTime = dtDateTime.AddSeconds(photoTime2).ToLocalTime();
                               photoData.CreateAt = dtDateTime;
                             


                                if (businessTypeCd == "420011")
                                {
                                    fullName = "1SEP2SEP3SEP420011SEP"  + photoTime1;

                                }else{
                                    fullName = shortName;
                                }
                                

                                photoData.PhotoName = fullName;
                                if (photoData.BusinessTypeCd == "420001")
                                {
                                    photoData.DisplayName = photoData.StoreId + "_01." + exName;
                                }
                                else
                                {
                                    photoData.DisplayName = photoData.StoreId + "_03." + exName;
                                }

                                strUrl = "http://" + yuing + "/" + shortName + "?imageMogr2/auto-orient/thumbnail/360x640!/blur/1x0/quality/75";
                                accUrl = DownloadManager.CreateSignedUrl(qiniuHelp.gMac, strUrl, 3600);
                                photoData.PhotoURL = accUrl;

                                saveUrl = Settings.Instance.photoSaveAllPath + photoData.PhotoName;
                               var result = DownloadManager.Download(photoData.PhotoURL, saveUrl);
                                //var result = DownloadManager.Download(photoData.PhotoURL, saveUrl);

                               // && result.RefText.IndexOf("Error") == -1

                                if (result.Code == 200)
                                {
                                    
                                    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "---------" + shortName + "Picture Download Success ");
                                    photoList.Add(photoData);
                               


                                }
                                else if (result.Code == 404)
                                {
                                    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "----Picture Url Incorrect-----" + shortName + result.Code);
                              

                                }
                                else if (result.Code == -256)
                                {

                                    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "----IP exceeds the IP segment configured by the firewall-----" + shortName + result.Code + "------" + result.RefText);
                                    status = 0;
                                    break;
                                }
                                else {
                                    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "----unknown HTTP code-----" + shortName + result.Code + "------" + result.RefText);
                                }

                            }
                            else {

                                Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "---------" + shortName + "Picture Name Incorrect");
                              
                            }                       
                                        
                 }
                }
                catch (Exception ex)
                {
                    status = 0;
                    Log.Error(MethodBase.GetCurrentMethod().DeclaringType, "foreach failed" + keyFile, ex);
                    
                }

                if (status == 1)
                {

                    DateTime s = DateTime.Parse(photoEndDate);
                   
                    long epoch = (s.ToUniversalTime().Ticks - 621355968000000000) ;


                    putTime = epoch;
                }
           
                

                // Log.Info(MethodBase.GetCurrentMethod().DeclaringType, putTime.ToString());
                
                Settings.setConfig("putTime", putTime.ToString());


                return photoList;
            }
            catch (Exception ex)
            {
                Log.Error(MethodBase.GetCurrentMethod().DeclaringType, "Failed to get photolist from QiniuCloud" + keyFile, ex);
                //if (UpdateDownloadSuccess(objectId))
                //    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "Exception delete the photo" + keyFile);
                //else
                //    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "Exception failed to delete the photo" + keyFile);
                return null;
            }
        }

        public void SavePhoto(PhotoData photoData)
        {
            try
            {
                string saleCenterName = "";
                string _strSpliter = "\\";
                string _strPhototypename = "";
                saleCenterName = photoData.RouteId == null ? string.Empty : Utility.GetSalesCenterByRoute(photoData.RouteId);
                string prjectstoreDirectory = saleCenterName + _strSpliter +
                        photoData.RouteId + _strSpliter;

                if (photoData.BusinessTypeCd == "420003")
                {
                    _strPhototypename = "活动";
                    prjectstoreDirectory = prjectstoreDirectory + _strPhototypename + _strSpliter;
                }
                else if (photoData.BusinessTypeCd == "420001")
                {
                    _strPhototypename = "门招";
                    prjectstoreDirectory = prjectstoreDirectory + _strPhototypename + _strSpliter;
                }

                string saveUrl = Settings.Instance.photoSaveAllPath + prjectstoreDirectory + photoData.PhotoName;
                var result = DownloadManager.Download(photoData.PhotoURL, saveUrl);

                if (result.Code == 200 && result.RefText.IndexOf("Error") > -1)
                {
                    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "success to save outletPhotos");
                }
                else
                {
                    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, result.RefText);
                }
            }
            catch (Exception ex)
            {
                Log.Error(MethodBase.GetCurrentMethod().DeclaringType, "failed to save outletPhotos", ex);
            }
        }

        public bool UpdateDownloadSuccess(string fileKey, string bucket)
        {
            try
            {
                QiniuHelper qiniuHelper = new QiniuHelper(Settings.Instance.QiniuAccessKey, Settings.Instance.QiniuSecretKey, "");
                var result = qiniuHelper.BucketManager.Delete(bucket, fileKey);

                if (result.Code == 200)
                {
                    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "Success to delete the photo,fileKey:[" + fileKey + "]");
                }
                else
                {
                    Log.Info(MethodBase.GetCurrentMethod().DeclaringType, "Failed to delete the photo,fileKey:[" + fileKey + "]");
                }

                return true;
            }
            catch (Exception ex)
            {
                Log.Error(MethodBase.GetCurrentMethod().DeclaringType, "Failed to download flag,fileKey:[" + fileKey + "]", ex);
                return false;
            }

        }

    }
   
}
